package com.zd.service;

import com.zd.config.MinioConfig;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartResolver;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Service
public class MinioService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConfig minioConfig;

    public void createBucket(String bucketName) throws Exception {
        if(!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
    }

    public String uploadFile(String bucketName, MultipartFile file) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException {
        String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")) ;
        String fileName = UUID.randomUUID().toString() + extName ;
        System.out.println("==========================>" + fileName);
        minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(fileName)
                .stream(file.getInputStream(),file.getInputStream().available(),-1)
                .contentType(file.getContentType()).build()) ;
        return minioConfig.getEndpoint() + "/" + minioConfig.getBucketName() + "/" + fileName ;
    }

    public InputStream downloadFile(String bucketName, String filename) throws Exception {
        return minioClient.getObject(GetObjectArgs.builder()
                .bucket(bucketName)
                .object(filename)
                .build());
    }


}
